﻿using AyuBookmark.Common.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace AyuBookmark.WinForm.Dialogs
{
    /// <summary>
    /// 分类管理对话框
    /// </summary>
    public partial class CategoryManager : Form
    {
        // UI控件声明
        private TreeView treeCategories;
        private Button btnAdd;
        private Button btnEdit;
        private Button btnDelete;
        private Button btnSave;
        private Button btnCancel;
        private Panel panelTree;
        private Panel panelButtons;
        private ContextMenuStrip contextMenu;
        private ToolStripMenuItem menuAdd;
        private ToolStripMenuItem menuEdit;
        private ToolStripMenuItem menuDelete;

        /// <summary>
        /// 获取或设置分类列表
        /// </summary>
        public List<Category> Categories { get; set; }

        /// <summary>
        /// 获取修改后的分类列表
        /// </summary>
        public List<Category> ModifiedCategories { get; private set; }

        public CategoryManager(List<Category> categories)
        {
            InitializeComponent();
            Categories = categories ?? new List<Category>();
            ModifiedCategories = new List<Category>();
            InitializeUI();
            LoadCategories();
        }

        private void InitializeComponent()
        {
            // 窗体基础设置
            this.SuspendLayout();
            this.Text = "分类管理";
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.ClientSize = new Size(500, 400);
            this.BackColor = SystemColors.Window;
            this.Padding = new Padding(10);

            // 分类树形视图
            this.treeCategories = new TreeView();
            this.treeCategories.Dock = DockStyle.Fill;
            this.treeCategories.HideSelection = false;
            this.treeCategories.FullRowSelect = true;
            this.treeCategories.ShowLines = false;
            this.treeCategories.ShowPlusMinus = false;
            this.treeCategories.ShowRootLines = false;
            this.treeCategories.DrawMode = TreeViewDrawMode.OwnerDrawAll;
            this.treeCategories.DrawNode += OnDrawTreeNode;
            this.treeCategories.AfterSelect += OnCategorySelected;
            this.treeCategories.NodeMouseDoubleClick += OnNodeDoubleClick;
            this.treeCategories.Font = new Font("Microsoft YaHei", 9f);

            // 树形视图面板
            this.panelTree = new Panel();
            this.panelTree.Dock = DockStyle.Fill;
            this.panelTree.Padding = new Padding(0, 0, 0, 50);

            // 按钮面板
            this.panelButtons = new Panel();
            this.panelButtons.Dock = DockStyle.Bottom;
            this.panelButtons.Height = 50;
            this.panelButtons.BackColor = SystemColors.Control;

            // 添加按钮
            this.btnAdd = new Button();
            this.btnAdd.Text = "添加";
            this.btnAdd.Size = new Size(80, 30);
            this.btnAdd.Location = new Point(20, 10);
            this.btnAdd.Font = new Font("Microsoft YaHei", 9f);
            this.btnAdd.Click += (s, e) => AddCategory();

            // 编辑按钮
            this.btnEdit = new Button();
            this.btnEdit.Text = "编辑";
            this.btnEdit.Size = new Size(80, 30);
            this.btnEdit.Location = new Point(110, 10);
            this.btnEdit.Font = new Font("Microsoft YaHei", 9f);
            this.btnEdit.Click += (s, e) => EditCategory();
            this.btnEdit.Enabled = false;

            // 删除按钮
            this.btnDelete = new Button();
            this.btnDelete.Text = "删除";
            this.btnDelete.Size = new Size(80, 30);
            this.btnDelete.Location = new Point(200, 10);
            this.btnDelete.Font = new Font("Microsoft YaHei", 9f);
            this.btnDelete.Click += (s, e) => DeleteCategory();
            this.btnDelete.Enabled = false;

            // 保存按钮
            this.btnSave = new Button();
            this.btnSave.Text = "保存";
            this.btnSave.Size = new Size(80, 30);
            this.btnSave.Location = new Point(310, 10);
            this.btnSave.Font = new Font("Microsoft YaHei", 9f, FontStyle.Bold);
            this.btnSave.Click += (s, e) => SaveCategories();

            // 取消按钮
            this.btnCancel = new Button();
            this.btnCancel.Text = "取消";
            this.btnCancel.Size = new Size(80, 30);
            this.btnCancel.Location = new Point(400, 10);
            this.btnCancel.Font = new Font("Microsoft YaHei", 9f);
            this.btnCancel.Click += (s, e) => this.DialogResult = DialogResult.Cancel;

            // 上下文菜单
            this.contextMenu = new ContextMenuStrip();
            this.menuAdd = new ToolStripMenuItem("添加分类");
            this.menuEdit = new ToolStripMenuItem("编辑分类");
            this.menuDelete = new ToolStripMenuItem("删除分类");
            this.contextMenu.Items.AddRange(new ToolStripItem[] { menuAdd, menuEdit, menuDelete });
            this.menuAdd.Click += (s, e) => AddCategory();
            this.menuEdit.Click += (s, e) => EditCategory();
            this.menuDelete.Click += (s, e) => DeleteCategory();
            this.treeCategories.ContextMenuStrip = contextMenu;

            // 添加控件到面板
            this.panelTree.Controls.Add(this.treeCategories);
            this.panelButtons.Controls.Add(this.btnAdd);
            this.panelButtons.Controls.Add(this.btnEdit);
            this.panelButtons.Controls.Add(this.btnDelete);
            this.panelButtons.Controls.Add(this.btnSave);
            this.panelButtons.Controls.Add(this.btnCancel);

            // 添加控件到窗体
            this.Controls.Add(this.panelTree);
            this.Controls.Add(this.panelButtons);

            this.ResumeLayout(false);
        }

        private void InitializeUI()
        {
            // 初始化UI状态
            UpdateButtonStates();
        }

        private void LoadCategories()
        {
            this.treeCategories.BeginUpdate();
            this.treeCategories.Nodes.Clear();

            // 构建分类树
            var rootCategories = Categories.Where(c => c.ParentId == null).ToList();
            foreach (var category in rootCategories)
            {
                var node = CreateTreeNode(category);
                this.treeCategories.Nodes.Add(node);
                AddChildNodes(node, category.Id);
            }

            this.treeCategories.EndUpdate();
        }

        private TreeNode CreateTreeNode(Category category)
        {
            var node = new TreeNode(category.Name)
            {
                Tag = category,
                ForeColor = ColorTranslator.FromHtml(category.Color),
                NodeFont = new Font("Microsoft YaHei", 9f, FontStyle.Bold)
            };
            return node;
        }

        private void AddChildNodes(TreeNode parentNode, int parentId)
        {
            var childCategories = Categories.Where(c => c.ParentId == parentId).ToList();
            foreach (var category in childCategories)
            {
                var childNode = CreateTreeNode(category);
                parentNode.Nodes.Add(childNode);
                AddChildNodes(childNode, category.Id);
            }
        }

        private void OnDrawTreeNode(object sender, DrawTreeNodeEventArgs e)
        {
            if (e.Node == null) return;

            // 计算绘制区域
            var bounds = e.Bounds;
            bounds.Width = this.treeCategories.ClientSize.Width;

            // 背景色
            Color backColor = e.Node.IsSelected ? SystemColors.Highlight : SystemColors.Window;

            // 绘制背景
            using (var brush = new SolidBrush(backColor))
            {
                e.Graphics.FillRectangle(brush, bounds);
            }

            // 绘制图标和文本
            int offset = e.Node.Level * 20 + 8;
            var textRect = new Rectangle(
                bounds.X + offset,
                bounds.Y,
                bounds.Width - offset,
                bounds.Height);

            TextRenderer.DrawText(
                e.Graphics,
                e.Node.Text,
                e.Node.NodeFont ?? this.treeCategories.Font,
                textRect,
                e.Node.IsSelected ? SystemColors.HighlightText : e.Node.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Left);

            // 绘制展开/折叠图标
            if (e.Node.Nodes.Count > 0)
            {
                var iconRect = new Rectangle(
                    bounds.X + e.Node.Level * 20 + 4,
                    bounds.Y + (bounds.Height - 16) / 2,
                    16, 16);

                var iconChar = e.Node.IsExpanded ? '▼' : '▶';
                TextRenderer.DrawText(
                    e.Graphics,
                    iconChar.ToString(),
                    this.treeCategories.Font,
                    iconRect,
                    Color.Gray,
                    TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
            }
        }

        private void OnCategorySelected(object sender, TreeViewEventArgs e)
        {
            UpdateButtonStates();
        }

        private void OnNodeDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node != null)
            {
                EditCategory();
            }
        }

        private void UpdateButtonStates()
        {
            bool hasSelection = this.treeCategories.SelectedNode != null;
            this.btnEdit.Enabled = hasSelection;
            this.btnDelete.Enabled = hasSelection;
            this.menuEdit.Enabled = hasSelection;
            this.menuDelete.Enabled = hasSelection;
        }

        private void AddCategory()
        {
            var parentId = this.treeCategories.SelectedNode?.Tag is Category selectedCat
                ? selectedCat.Id
                : (int?)null;

            using (var dialog = new CategoryEditor(null, parentId))
            {
                if (dialog.ShowDialog(this) == DialogResult.OK)
                {
                    var newCategory = dialog.CurrentCategory;
                    Categories.Add(newCategory);

                    var newNode = CreateTreeNode(newCategory);
                    if (parentId == null)
                    {
                        this.treeCategories.Nodes.Add(newNode);
                    }
                    else
                    {
                        this.treeCategories.SelectedNode.Nodes.Add(newNode);
                        this.treeCategories.SelectedNode.Expand();
                    }

                    this.treeCategories.SelectedNode = newNode;
                    ModifiedCategories.Add(newCategory);
                }
            }
        }

        private void EditCategory()
        {
            if (this.treeCategories.SelectedNode?.Tag is Category category)
            {
                using (var dialog = new CategoryEditor(category))
                {
                    if (dialog.ShowDialog(this) == DialogResult.OK)
                    {
                        var updatedCategory = dialog.CurrentCategory;
                        category.Name = updatedCategory.Name;
                        category.Color = updatedCategory.Color;
                        category.ParentId = updatedCategory.ParentId;

                        this.treeCategories.SelectedNode.Text = category.Name;
                        this.treeCategories.SelectedNode.ForeColor = ColorTranslator.FromHtml(category.Color);
                        this.treeCategories.Invalidate();

                        ModifiedCategories.Add(category);
                    }
                }
            }
        }

        private void DeleteCategory()
        {
            if (this.treeCategories.SelectedNode?.Tag is Category category)
            {
                var result = MessageBox.Show(
                    $"确定要删除分类 '{category.Name}' 吗？所有子分类也将被删除。",
                    "确认删除",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning);

                if (result == DialogResult.Yes)
                {
                    // 从集合中移除
                    Categories.RemoveAll(c => c.Id == category.Id || c.ParentId == category.Id);

                    // 添加到修改列表
                    ModifiedCategories.Add(category);
                    ModifiedCategories.AddRange(
                        Categories.Where(c => c.ParentId == category.Id)
                    );

                    // 从树中移除
                    this.treeCategories.Nodes.Remove(this.treeCategories.SelectedNode);
                    UpdateButtonStates();
                }
            }
        }

        private void SaveCategories()
        {
            this.DialogResult = DialogResult.OK;
        }

        public static DialogResult ShowManager(IWin32Window owner, List<Category> categories)
        {
            using (var dialog = new CategoryManager(categories))
            {
                return dialog.ShowDialog(owner);
            }
        }
    }
}